const std = @import("std");
const Code = @import("Code.zig");

pub fn main() anyerror!void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(gpa.deinit() == .ok);
    const allocator = gpa.allocator();

    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    if (args.len < 2) {
        std.log.err("Usage: {s} <file.asm>", .{args[0]});
        return;
    }

    // open asm file
    const cwd = std.fs.cwd();
    const asmfile = try cwd.openFile(args[1], .{});
    defer asmfile.close();

    // truncate hack file for writing
    const filebase = std.mem.trimRight(u8, args[1], "asm");
    const hackfilename = try std.mem.concat(allocator, u8, &.{ filebase, "hack" });
    defer allocator.free(hackfilename);
    const hackfile = try cwd.createFile(hackfilename, .{ .truncate = true });
    defer hackfile.close();

    // parse asm
    var c: Code = try .init(allocator, asmfile);
    defer c.deinit();

    // write to hack file
    try c.compile(hackfile);
}
